<?php

namespace app\web\controller;

use app\common\controller\Fypay;
use app\common\service\NotifyService;
use think\facade\Env;
use think\Request;

/**
 * 富友支付回调
 */
class FuYouNotify extends Auth
{
    public $noNeedLogin = ['*'];

    public $config;
    public $pem;

    public function __construct(Request $request)
    {
        $this->config = config('fu_you_config');
        $this->config['random_str'] = $this->createNoncestr();//随机字符串
        $this->pem = file_get_contents(Env::get('app_path') . 'common/library/keypem.pem');

        parent::__construct($request);
    }


    /**
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\db\exception\DataNotFoundException
     */
    public function cs2payNotify(){

        if ($this->request->isPost()) {

            $post = $this->request->post();
//            $post = [
//                "addn_inf" => [],
//                "buyer_id" => "2088802303467591",
//                "ins_cd" => "08A9999999",
//                "mchnt_cd" =>"0002900F0370542",
//                "mchnt_order_no" => "D421126323978402",//商户订单号, 商户系统内部的订单号
//                "order_amt" => "1",//支付金额
//                "order_type" => "ALIPAY",//订单类型:ALIPAY，WECHAT
//                "random_str" => "R48NPTUCQHKM7WPJRWM0MJHM4DNYWH0S",
//                "reserved_bank_type" => "BANKCARD",//bankcard  //银行卡
//                "reserved_buyer_logon_id" => "zpl***@126.com",//买家在渠道登录账号
//                "reserved_channel_order_id" => "D421126323978402",//条码流水号，用户账单二维码对应的流水
//                "reserved_coupon_fee" => [],//优惠金额(分)
//                "reserved_fund_bill_list" =>  '[{"amount":"0.01","fundChannel":"BANKCARD","fundType":"CREDIT_CARD"}]',
//                "reserved_fy_settle_dt" => "20220421",//富友交易日期
//                "reserved_fy_trace_no" => "040000000324",//富友系统内部追踪号
//                "reserved_is_credit" => "1",
//                "reserved_risk_info" => [],
//                "reserved_settlement_amt" => "1",//应结算订单金额，分为单位的整数。只有成功交易才会返回,如果使用了商户免充值优惠券，该值为订单金额-商户免充值 如果没有使用商户免充值，该值等于订单金额
//                "reserved_txn_fin_ts" => "20220421114539",//用户支付时间yyyyMMddHHmmss
//                "result_code" => "000000",//返回码成功
//                "result_msg" => "SUCCESS",
//                "sign" => "Nck/z05ohVKnbM5wAnQzJsiiIxPfXSY1onVG4jjxHJB/QXMdTPHNPgm2iIgo1px4h72TEMiR3+ciQEGqR4xe1rn7qd3yv2ES9g5Eent40BUlrxjuB4MxSC4HSOAKnoGf9BAWV6/SeKdSrcz22ApZodiyDDsVOl1N6zbS07JsKus=",
//                "term_id" => "88888888",
//                "trans_stat" => "SUCCESS",
//                "transaction_id" => "2022042122001467591419137254",//渠道订单号
//                "trans_stat_msg" => "成功",
//            ];
            file_put_contents('fuyou.txt',$post,FILE_APPEND);
            $pay = new FuYouPays();
            $sign = $pay->checkSign($post);
            if ($sign) {
                $result = NotifyService::paySuccess($post['mchnt_order_no'],$post['order_amt'],$post['transaction_id'],$post['order_type']);
                $this->result($result['msg'], $result['data'], $result['code']);
            } else {
                dump('非法请求');
                exit;
            }
        }
        $this->result('无效的请求', '', 204);

    }




    //主扫统一下单回调
    public function notify()
    {
        $param = $this->request->param();
        $Fypay = new Fypay();
        $xml = URLdecode($param['req']);
        // 转成php数组
        $arr = $Fypay->toArray($xml);
        //file_put_contents('xml.txt',json_encode($arr));
        //验证签名
        if ($arr['result_code'] == '000000') {
            $data = [
                'curr_type' => $arr['curr_type'],
                'ins_cd' => $arr['ins_cd'],
                'mchnt_cd' => $arr['mchnt_cd'],
                'mchnt_order_no' => $arr['mchnt_order_no'],
                'order_amt' => $arr['order_amt'],
                'order_type' => $arr['order_type'],
                'random_str' => $arr['random_str'],
                'result_code' => $arr['result_code'],
                'result_msg' => $arr['result_msg'],
                'settle_order_amt' => $arr['settle_order_amt'],
                'term_id' => $arr['term_id'],
                'transaction_id' => $arr['transaction_id'],
                'txn_fin_ts' => $arr['txn_fin_ts'],
                'user_id' => $arr['user_id'],
            ];
            //进行签名验证
            $sign = $Fypay->make_sign($data);
            if ($sign == $arr['sign']) {
                //进行订单操作
                dump($arr);
                exit;
            } else {
                dump('非法请求');
                dump($arr);
                exit;
            }
        } else {
            echo "回调失败";
            exit;
        }
    }

    //订单退款
    public function refund()
    {
        $Fypay = new Fypay();
        $order = [
            'order_type' => 'ALIPAY',
            'mchnt_order_no' => 'D413297888384921',//平台的订单号
            'refund_order_no' => $this->create_ordersn(),//商户退款单号
            'total_amt' => 2,//总金额
            'refund_amt' => 2,//退款金额
            'operator_id' => 'zhangsan',//操作员
        ];
        $res = $Fypay->OrderRefund($order, $this->pem, $this->config);
        dump($res);
        exit;
    }

    //退款查询
    public function searchrefund()
    {
        $Fypay = new Fypay();
        $order = [
            'refund_order_no' => 'D413323575870098',//退款订单号
        ];
        $res = $Fypay->RefundQuery($order, $this->pem, $this->config);
        dump($res);
        exit;
    }

    //作用：产生随机字符串，不长于32位
    private function createNoncestr($length = 32)
    {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    //生成订单号
    private function create_ordersn()
    {
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N');
        $orderSn = $yCode[intval(date('Y')) - 2019] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
        return $orderSn;
    }
}